/**
 * 
 */
package freedom.needle.mod;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freedom.needle.util.WeblogicUtil;

/**
 * @author charlie
 *
 */
public class DynamicModStrategyDeamon implements Runnable {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private long interval = 1000;//刷新时间间隔
	private long keepMillis = 15*60*1000;//modValue保持时间
	private DynamicModStrategy dymamicModStrategy;

	/**
	 * @param interval
	 * @param keepMillis
	 * @param dynamicModStrategy
	 */
	public DynamicModStrategyDeamon(long interval, long keepMillis, DynamicModStrategy dynamicModStrategy) {
		super();
		this.interval = interval;
		this.keepMillis = keepMillis;
		this.dymamicModStrategy = dynamicModStrategy;
	}



	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(interval);
				refresh();
			} catch (InterruptedException e) {
				logger.warn("sleep is interrupted!");
			} catch(Exception e) {
				logger.error("refresh error!");
			}
		}
	}

	/**
	 * 
	 */
	private void refresh() {
		long now = System.currentTimeMillis();
		int dynamicModValue = (int) ((now / keepMillis + WeblogicUtil.getId()) % WeblogicUtil.getNodes());
		dymamicModStrategy.setModValue(dynamicModValue);
	}

}
